import sys
import socket
import struct
import json
import threading, time, datetime
import pyautogui
import logging

logging.basicConfig(filename='gp.log',level=logging.INFO)

 
tt = 0.001
def auto_buy(stock_code, amount):
    # 点击买入
    pyautogui.click(x=45, y=83) #点击买入
    time.sleep(tt)    
    pyautogui.click(x=305, y=122) #点击证券代码
    time.sleep(tt)
    # 输入股票代码
    pyautogui.typewrite(stock_code)
    time.sleep(tt)
    pyautogui.press('enter')
    time.sleep(tt)
    pyautogui.press('enter')
    time.sleep(tt)
    # 输入买入数量
    pyautogui.typewrite(str(amount))
    time.sleep(tt)
    # 确认买入
    pyautogui.click(x=338, y=243)
    time.sleep(tt)
    pyautogui.click(x=900, y=617)

def auto_sell(stock_code, amount):
    #  点击卖出
    pyautogui.click(x=52, y=100)
    time.sleep(tt)
    pyautogui.click(x=305, y=122) #点击证券代码
    time.sleep(tt)
    # 输入股票代码
    pyautogui.typewrite(stock_code)
    time.sleep(tt)
    pyautogui.press('enter')
    time.sleep(tt)
    pyautogui.press('enter')
    time.sleep(tt)
    # 输入卖出数量
    pyautogui.typewrite(str(amount))
    time.sleep(tt)
    # 确认买入
    pyautogui.click(x=338, y=243)
    time.sleep(tt)
    pyautogui.click(x=900, y=617)
    
def handle_gp(args):
    #print(args)
    
    #return
    s = args[0]
    l = s.split('|')
    dict = {}
    for i in l:
        j = i.split('_')
        dict[j[0]] = j[1]
    
    print(dict)
    #print('ok')
    
    #return
    ss = dict
    token = ss['token']
    if ss:
        #print(ss['action'])
        
        if ss['action'] == 'buy':
            if token == '123':
                stock = ss['zqdm'][:6]
                num = ss['qty']
                strategy = ss['strategy']
                trade_time = ss['tradetime']
                now_time = ss['time']

                logging.info(f'%s %s %s %s %s %s' % (stock, num, 'buy',trade_time, strategy, now_time))
                #auto_buy(stock, num)
        elif ss['action'] == 'sell':
            if token == '123':
                stock = ss['zqdm'][:6]
                num = ss['qty']
                strategy = ss['strategy']
                trade_time = ss['tradetime']
                now_time = ss['time']
                
                logging.info(f'%s %s %s %s %s %s' % (stock, num, 'sell',trade_time, strategy, now_time))
                #auto_sell(stock, num)
        
    #     print("recv params:")
    #     for i, arg in enumerate(args, 1):
    #         print(f"params {i}: {arg}")
    
#获取当前时间
def get_now():
    from datetime import datetime
    current_datetime = datetime.now()
    formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
    return formatted_datetime

def main():
    # sys.argv[0] 是脚本名称
    # sys.argv[1:] 是传递的参数
    args = sys.argv[1:]
    
    if not args:
        print("Usage: python script.py [arg1] [arg2] ...")
        return
    #do it
    handle_gp(args)

if __name__ == "__main__":
    main()